package com.zt.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.ObjectListing;
import com.aliyuncs.exceptions.ClientException;
import com.zt.pojo.UploadProperties;
import com.zt.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class UploadServiceImpl implements UploadService  {
    @Autowired
    private UploadProperties uploadProperties;

    @Override
    public String upload(MultipartFile file) throws ClientException {

        String endpoint = uploadProperties.getEndpoint();
        String bucketName = uploadProperties.getBucket();
        String pageUrl = uploadProperties.getPageurl();
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        //截取文件的格式字段
        String fileName = file.getOriginalFilename();
        //获取文件后缀
        String ext = fileName.substring(fileName.lastIndexOf("."));
        String objectName = UUID.randomUUID()+ext;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        try(InputStream inputStream = file.getInputStream()) {
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null){
                ossClient.shutdown();
            }
        }
        String url = pageUrl + objectName;
        return url;
    }

    public Set<String> list() throws Exception {
        String endpoint = uploadProperties.getEndpoint();
        String bucketName = uploadProperties.getBucket();

        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        //文件上传
        try {
            ObjectListing objectListing = ossClient.listObjects(bucketName);
            return objectListing.getObjectSummaries().stream().map(e -> e.getKey()).collect(Collectors.toSet());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public void remove(List<String> keys) throws Exception {
        String endpoint = uploadProperties.getEndpoint();
        String bucketName = uploadProperties.getBucket();

        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        //文件上传
        try {

            DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys).withEncodingType("url"));
            List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
            try {
                for (String obj : deletedObjects) {
                    String deleteObj = URLDecoder.decode(obj, "UTF-8");
                    System.out.println(deleteObj);
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
